package com.lgl.scsheader.system.filter;

import com.lgl.scsapi.system.model.SysUser;
import com.lgl.scsapi.util.utils.Constants;
import com.lgl.scsheader.base.controller.BaseController;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证过滤器
 */
public class LoginFilter extends BaseController implements Filter {

	/**
	 * 初始化
	 */
	@Override
	public void init(FilterConfig fc) {
	}
	@Override
	public void destroy() {

	}
	@Override
	public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String path = request.getServletPath();
		//shiro管理的session
		Session session = SecurityUtils.getSubject().getSession();
		SysUser loginUser = (SysUser)session.getAttribute(Constants.SESSION_USER);
		//如果是需要校验的请求且用户未登录,&& !SecurityUtils.getSubject().isAuthenticated()
        if (!"/".equals(path) && !path.matches(Constants.HEADER_NO_INTERCEPTOR_PATH) && loginUser == null) {
			//返回登录页面
			response.sendRedirect("/");
			return;
        }
		// 调用下一过滤器
		chain.doFilter(req, res);
	}
}